package com.tukez.tmdb.http
import org.apache.http.client.fluent.Request
import org.apache.http.client.fluent.Form
import org.apache.http.message.BasicNameValuePair
import org.apache.http.NameValuePair
import scala.collection.JavaConversions._
import org.apache.http.client.fluent.Response
import java.util.concurrent.Semaphore
import org.joda.time.Duration
import java.util.concurrent.DelayQueue
import java.util.concurrent.Delayed
import java.util.concurrent.TimeUnit
import org.apache.http.util.EntityUtils

class HttpClient extends IHttpClient {

  override def get(url: String): HttpResponse = {
    val response = Request.Get(url).execute()
    createHttpResponse(response)
  }

  override def post(url: String, params: Map[String, String]): HttpResponse = {
    val paramIterable = for ((name, value) <- params) yield new BasicNameValuePair(name, value)
    val response = Request.Post(url).bodyForm(asJavaIterable(paramIterable)).execute()
    createHttpResponse(response)
  }

  private def createHttpResponse(response: Response): HttpResponse = {
    val res = response.returnResponse
    val statusCode = res.getStatusLine.getStatusCode
    val body = EntityUtils.toString(res.getEntity)
    HttpResponse(statusCode, body)
  }
}